﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;

namespace eCommerce.DataAccess
{
    public class CartDA
  {
      #region Properties
	public Guid CartID { get; set; }
	public Boolean Exists { get; set; }
	public String CartIP = HttpContext.Current.Request.ServerVariables["REMOTE_HOST"];
	//public CartProduct[] Products;
	public ArrayList Products = new ArrayList();
	public Int32 ProductsQty = 0;
	public Double Total = 0;
	#endregion

	#region Constructors
	public CartDA()
	{
		GetCartID();
	}
	#endregion

	public void AddProduct(Int32 productID, Int32 productType, Int32 qty)
	{
		CartProduct.Add(CartID, productID, productType, qty);
	}

	public void GetCartID()
	{
		try
		{
			if (SiteFunctions.CookiesEnabled)
			{
				if (HttpContext.Current.Request.Cookies["cartid"].Value.Length > 0)
				{
					CartID = new Guid(SqlGuid.Parse(HttpContext.Current.Request.Cookies["cartid"].Value).ToString());
				}
				else if (HttpContext.Current.Session["cartid"] != null)
				{
					CartID = new Guid(SqlGuid.Parse(HttpContext.Current.Session["cartid"].ToString()).ToString());
				}
			}
			else if (HttpContext.Current.Session["cartid"] != null)
			{
				CartID = new Guid(SqlGuid.Parse(HttpContext.Current.Session["cartid"].ToString()).ToString());
			}
			else
			{
				CartID = Guid.NewGuid();
			}
		}
		catch
		{
			CartID = Guid.NewGuid();
		}
		GetCart();
	}

	public void GetCart()
	{
        {
            bool validGuid = false;
            while (!validGuid)
            {
                eCommerceDataContext dataContext = new eCommerceDataContext();
                var cart = dataContext.custom_getcart(CartID, CartIP);
               
                if (cart != null)
                {
                    validGuid = true;
                    UpdateCart();
                }
                else
                {
                    CartID = Guid.NewGuid();
                    InsertCart();
                }
                
            }
            HttpContext.Current.Session["cartid"] = CartID.ToString();
            if (HttpContext.Current.Response.Cookies != null)
            {
                HttpContext.Current.Response.Cookies["cartid"].Value = CartID.ToString();
                HttpContext.Current.Response.Cookies["cartid"].Expires = DateTime.Now.AddDays(1d);
            }
            GetProducts();
        }
	}

	protected void InsertCart()
	{
        using (eCommerceDataContext dataContext = new eCommerceDataContext())
        {
            //dataContext.custom_insertcart(CartID, CartIP);
            //dataContext.SubmitChanges();

            Cart cart = new Cart {cartid = CartID, cartip = CartIP};
            //var cartInsert = dataContext.custom_insertcart(CartID, CartIP);
            dataContext.Carts.InsertOnSubmit(cart);
            dataContext.SubmitChanges();
        }
	}

	protected void UpdateCart()
	{
        using (eCommerceDataContext dataContext = new eCommerceDataContext())
        {

            Cart cart = new Cart {cartid = CartID, cartip = CartIP};
            dataContext.SubmitChanges();
        }
    }

	protected void GetProducts()
	{
         using (eCommerceDataContext dataContext = new eCommerceDataContext())
         {
             //var cart = dataContext.custom_getcartproducts(CartID);

             var oProductInfo = (from pr in dataContext.Cart_Products
                                 where pr.cartid == CartID && pr.qty > 0
                                 select pr);

             foreach (Cart_Product product in oProductInfo)
             {

                     Int32 producttype = Int32.Parse(product.producttype.ToString());
                     Int32 productid = Int32.Parse(product.productid.ToString());

                     CartProduct aProduct = new CartProduct(CartID, productid, producttype);
                     if (aProduct.Exists)
                     {
                         Products.Add(aProduct);
                         ProductsQty += aProduct.Quantity;
                         Total += aProduct.Quantity * aProduct.PriceGBP * (1 - (aProduct.Discount / 100));
                     }
                 
             }
            
                
                 
             
         }
   }
	    //using (SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString))
        //{
        //    sqlConn.Open();
        //    SqlCommand sqlcmd = new SqlCommand("custom_getcartproducts", sqlConn);
        //    sqlcmd.CommandType = CommandType.StoredProcedure;
        //    sqlcmd.Parameters.Add(new SqlParameter("@cartid", CartID));
        //    SqlDataReader reader = sqlcmd.ExecuteReader();
        //    while (reader.Read())
        //    {
        //        Int32 producttype = Int32.Parse(reader["producttype"].ToString());
        //        Int32 productid = Int32.Parse(reader["productid"].ToString());
        //        if (producttype == 3)
        //        {
        //        }
        //        else
        //        {
        //            CartProduct aProduct = new CartProduct(CartID, productid, producttype);
        //            if (aProduct.Exists)
        //            {
        //                Products.Add(aProduct);
        //                ProductsQty += aProduct.Quantity;
        //                Total += aProduct.Quantity * aProduct.PriceGBP * (1 - (aProduct.Discount / 100));
        //            }
        //        }
        //    }
        //}
	//}

	public static void Reset()
	{
	    HttpContext.Current.Session["cartid"] = "";
	    HttpContext.Current.Response.Cookies["cartid"].Value = "";
	    HttpContext.Current.Response.Cookies["cartid"].Expires = DateTime.Now;
	    if (HttpContext.Current.Request.Cookies["cartid"] != null)
	    {
	        HttpCookie myCookie = new HttpCookie("cartid");
	        myCookie.Expires = DateTime.Now.AddDays(-1d);
	        HttpContext.Current.Response.Cookies.Add(myCookie);
	    }
	}
    }

}
